package com.lijie.ljblog.socketAPI;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @Description
 * @Author lijie
 * @Date 2022/8/24 9:52
 **/
@Slf4j
@Component
public class TextWebSocketAPI extends TextWebSocketHandler {
    @Override
    //用户建立连接后触发的方法
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("sessionId="+session.getId());
        String query = session.getUri().getQuery();
        String[] split = query.split("=");
        log.info("userId"+split[1]);
        log.info("连接成功");

    }

    @Override
    //收到文本消息后触发的方法
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("收到消息 : " + message.getPayload());
        session.sendMessage(new TextMessage("我收到了你的消息" + message.getPayload()));
        session.sendMessage(new TextMessage("第二次发消息" + message.getPayload()));
    }

    @Override
    //触发异常后触发的方法
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.info("连接异常");
    }

    @Override
    //关闭连接后触发的方法
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("关闭连接");

        String id = session.getId();
    }


}
